
const Expense = require('../model/expense.model')
const ExpImg = require('../model/expImg.model')
const { queryUtil } = require('../utils/query.util')
class ExpenseService {
    async createExpense(expense) {

        const res = await Expense.create(expense)
        return res ? res.dataValues : null
    }

    async queryAll(whereOpt) {
        // return await Expense.findAll({ where: whereOpt})
        return await Expense.findAll({ include: { model: ExpImg, attributes: ['expId', 'path'] }, where: whereOpt })
        // console.log(res.dataValues);

    }

    async adminQueryAll(pageNum, pageSize, whereOpt) {
        const offset = (pageNum - 1) * pageSize
        const limit = pageSize * 1
        // console.log(whereOpt);
        const rows = await Expense.findAll({
            include: { model: ExpImg, attributes: ['expId', 'path'] },
            where: whereOpt,
            offset,
            limit
        })
        const count=await Expense.count({where:whereOpt})
        // console.log(rows);
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows,
        }

    }

    async updateById(expense) {
        const whereOpt = { id: expense.id }
        const { id, ...newExpense } = expense
        const res = await Expense.update(newExpense, { where: whereOpt })
        return res[0] > 0 ? true : false
    }

    async removeById(id) {
        const res = await Expense.destroy({ where: { id } })
    }
}

module.exports = new ExpenseService()